Vue3 自定义Hook 您所在的位置:网站首页 vue3 mixins 使用 Vue3 自定义Hook

Vue3 自定义Hook

2022-12-21 02:10| 来源: 网络整理| 查看: 265

主要用来处理复用代码逻辑的一些封装

这个在vue2 就已经有一个东西是Mixins

mixins就是将这些多个相同的逻辑抽离出来,各个组件只需要引入mixins,就能实现一次写代码,多组件受益的效果。

弊端就是 会涉及到覆盖的问题组件的data、methods、filters会覆盖mixins里的同名data、methods、filters。 变量来源不明确(隐式传入),不利于阅读,使代码变得难以维护。

Vue3 的自定义的hook

Vue3 的 hook函数 相当于 vue2 的 mixin, 不同在与 hooks 是函数 Vue3 的 hook函数 可以帮助我们提高代码的复用性, 让我们能在不同的组件中都利用 hooks 函数 Vue3 hook 库Get Started | VueUse

案例

import { onMounted } from 'vue' type Options = {    el: string } ​ type Return = {    Baseurl: string | null } export default function (option: Options): Promise { ​    return new Promise((resolve) => {        onMounted(() => {            const file: HTMLImageElement = document.querySelector(option.el) as HTMLImageElement;            file.onload = ():void => {                resolve({                    Baseurl: toBase64(file)               })           }       })        const toBase64 = (el: HTMLImageElement): string => {            const canvas: HTMLCanvasElement = document.createElement('canvas')            const ctx = canvas.getContext('2d') as CanvasRenderingContext2D            canvas.width = el.width            canvas.height = el.height            ctx.drawImage(el, 0, 0, canvas.width,canvas.height)            console.log(el.width);                        return canvas.toDataURL('image/png')           }   }) ​ } 复制代码


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有